<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="width: 100%; display: flex; flex-direction: column; height: 100vh;">
    <div style="display: flex; align-items: center; padding: 1px 15px;">
      <!-- 左侧新建按钮 -->
      <el-button class="idoo-details-add">新建</el-button>
      <!-- 右侧信息区域：垂直展示 -->
      <div style="display: flex; flex-direction: column; margin-left: 10px;">
        <span style="font-size: 15px;"> <el-button type="primary" link @click="handleBack">员工</el-button></span>
        <div style="display: flex; align-items: center; font-size: 14px; margin-top: 4px;">
          <span class="sub-title">{{ detailsTitle }}</span>
          <el-tooltip content="保存" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleSave">
              <UploadFilled />
            </el-icon>
          </el-tooltip>
          <el-tooltip content="撤销修改" placement="top" v-if="isFormChanged">
            <el-icon class="hover-icon" style="margin-left: 10px;" @click="handleRevert">
              <RefreshLeft />
            </el-icon>
          </el-tooltip>
        </div>
      </div>
    </div>
    <!-- 带阴影的分割线 -->
    <div class="divider"></div>
    <!-- 后续内容区域：背景色为淡灰色，填满剩余区域 -->
    <div class="content-section">
      <div style="display: flex; width: 100% ; height: calc(100vh - 50px)">
        <div style=" width: 65%; overflow-y: auto; margin-right: 10px;">
          <el-card style="box-shadow: none ;height: auto;">
            <el-form :model="staffForm" style="width: 100%;">
              <el-form-item label="" prop="name">
                <el-input v-model="staffForm.staffName"
                  style="font-size: 30px; height: 60px; line-height: 60px; width: 70%; padding: 10px;"
                  class="idoo-details-input" placeholder="员工姓名"></el-input>
              </el-form-item>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="员工编号">
                    <el-input v-model="staffForm.staffCode" style="width: 100%;" class="idoo-details-input"
                      placeholder=""></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="工作电子邮件">
                    <el-input v-model="staffForm.staffEmail" style="width: 100%;" class="idoo-details-input"
                      placeholder="例如：johndoe@example.com"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="部门">
                    <el-select v-model="voForm.deptName" placeholder="请选择业务" @click="changePIdClick('dept')"
                      class="idoo-details-select">
                    </el-select>
                    <IdooServiceChooseDialog v-model:visible="showDialog" :rowKey="'id'" :title="'选择部门'"
                      :url="_getDepartmentTableList" :wrapper="_dept_query_wrapper_config" :selectIds="staffForm.deptId"
                      :columns="_dept_config_columns" :is-multiple="false" @selected="handleSelectedDept" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="工作地点">
                    <el-input v-model="staffForm.staffJobAddress" style="width: 100%;" class="idoo-details-input"
                      placeholder=""></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="办公手机">
                    <el-input v-model="staffForm.staffPhone" style="width: 100%;" class="idoo-details-input"
                      placeholder=""></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="工作岗位">
                    <el-input v-model="staffForm.staffJobPost" style="width: 100%;" class="idoo-details-input"
                      placeholder="例如：销售经理"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="最近考核日期">
                    <el-date-picker type="date" v-model="staffForm.staffAssensmentDate" style="width: 100%;"
                      class="idoo-details-input" format="YYYY-MM-DD" clearable @change="getDateRange"></el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="直属领导">
                    <el-select v-model="voForm.managerName" placeholder="请选择员工" @click="changePIdClick('staff')"
                      class="idoo-details-select">
                    </el-select>
                    <IdooServiceChooseDialog v-model:visible="showDialogManager" :rowKey="'id'" :title="'选择直属领导'"
                      :url="_getStaffTableList" :wrapper="_staff_query_wrapper_config" :selectIds="staffForm.manager"
                      :columns="_staff_config_columns" :is-multiple="false" @selected="handleSelectedStaff" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                </el-col>
              </el-row>
              <el-row :gutter="20" style="margin-top: 20px;">
                <!-- 将标签页移到这里，表单下方 -->
                <el-tabs type="border-card" v-model="activeName" class="demo-tabs" @tab-click="tabHandleClick"
                  style="overflow-y: auto; height: auto;">
                  <el-tab-pane label="技能" name="skill">
                    <StaffDetailsSkill v-if="tabHandleClickName == 'skill'" />
                  </el-tab-pane>
                  <el-tab-pane label="薪资/绩效" name="salary">
                    <StaffSalary v-if="tabHandleClickName == 'salary'" />
                  </el-tab-pane>
                  <el-tab-pane label="合同" name="contract">Config</el-tab-pane>
                </el-tabs>
              </el-row>
            </el-form>
          </el-card>
        </div>

        <!-- 右侧：修改记录区域，保持背景色 -->
        <div style="width: 35%; padding: 5px; overflow-y: auto;" v-if="formId">
          <!-- 按钮行 -->
          <div style="display: flex;margin-bottom: 10px;">
            <el-button :icon="Edit" :class="recordRemark ? 'idoo-details-add' : 'el-button-primary'"
              :type="recordRemark ? 'primary' : ''" @click="recordRemarkChoose"></el-button>
            <el-button :icon="Search" :class="recordSearch ? 'idoo-details-add' : 'el-button-primary'"
              :type="recordSearch ? 'primary' : ''" @click="recordSearchChoose"></el-button>

            <el-input ref="searchRef" v-if="recordSearch" v-model="recordSearchInfo" placeholder="搜索：操作记录内容：操作人/字段名称/内容"
              style="margin-left: 50px;width:60%">
              <template #append>
                <el-button :icon="Search" @click="recordSearching" style="display:inherit !important;" />
              </template>
            </el-input>
          </div>
          <div v-if="recordRemark">
            <el-input type="textarea" v-model="recordRemarkInfo" class="record-remark-textarea"
              placeholder="记录详情内部说明..." style="width: 70%;"></el-input>
          </div>
          <div style="margin-top: 5px;" v-if="recordRemark">
            <el-button type="primary" @click="sendRecordRemark" size="large"
              style="width: 60px; height: 35px; font-size: small;">发送</el-button>
          </div>
          <!-- 操作记录组件 -->
          <Record :recordInfos="recordInfos" />
        </div>
      </div>
    </div>

  </div>
</template>
<script setup lang="ts">
import { nextTick, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { UploadFilled, RefreshLeft, Edit, Search } from '@element-plus/icons-vue';
import { ElMessageBox, type TabsPaneContext } from 'element-plus'
import type { StaffForm } from '@/types/employess/staff/types';
import { getChangedFields, updateWrapperBuilder } from '@/utils/form/updateFormHelper';
import { _getRecordInfos, _getStaffInfo, _getStaffTableList, _modifyStaffInfo, _saveRecordRemarkInfos, _saveStaffInfo, _searchRecordRemarkInfos } from '@/api/generic/employess/staff/list-api';
import router from '@/router';
import type { BaseRecordVo } from '@/types/basetypes';
import Record from '@/components/base/record/IdooRecord.vue';
import type { DepartmentForm } from '@/types/employess/department/types';
import { departmentConfig, staffManagerConfig } from './StaffDetailsSupports';
import { _getDepartmentTableList } from '@/api/generic/employess/department/list-api';
import StaffDetailsSkill from './staff-details-skill.vue';
import StaffSalary from './staff-details-salary.vue';
// 初始化表单数据
const staffForm = ref<StaffForm>({
  /** 租户编号*/
  tenantId: '',
  /** 部门ID；空则为公共客户数据*/
  deptId: '',
  /**员工名称 */
  staffName: '',
  /**员工编号 */
  staffCode: '',
  /**员工头衔*/
  staffTitleName: '',
  /** 手机号码*/
  staffPhone: '',
  /** 邮件地址 */
  staffEmail: '',
  /**工作地址*/
  staffJobAddress: '',
  /**工作岗位*/
  staffJobPost: '',
  /**直属领导（员工id）*/
  manager: '',
  /**最近考核日期*/
  staffAssensmentDate: '',
  /**创建部门*/
  createDept: '',
});
const voForm = ref({
  deptName: '',
  managerName: '',
})
// 监听表单变化
watch(() => staffForm.value, (newVal) => {
  console.log(staffForm.value);
  console.log(originalFormData.value)
  isFormChanged.value = JSON.stringify(newVal) !== JSON.stringify(originalFormData.value);
}, { deep: true });

const route = useRoute();
const detailsTitle = ref("");
const isFormChanged = ref(false);
let formId = route.query.id || "";
const recordInfos = ref<BaseRecordVo[]>([]);
const recordRemark = ref(false);
const recordRemarkInfo = ref("");
const recordSearch = ref(false);
const recordSearchInfo = ref("");
const searchRef = ref(null);
const originalFormData = ref<StaffForm>({});
//tabs初始加载
const activeName = ref('skill')
//tabs切换
const tabHandleClickName = ref('skill')
originalFormData.value = JSON.parse(JSON.stringify(staffForm.value));
const handleBack = () => {
  if (isFormChanged.value) {
    ElMessageBox.confirm('是否保存当前数据？', '确认保存', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await handleSave();
    }).catch(() => {
      router.push({ path: route.fullPath.replace('/add', '') })
    })
  } else {
    console.log(route.fullPath.replace('/add', ''))
    router.push({ path: route.fullPath.replace('/add', '') })
  }
}
// 保存处理函数
const handleSave = async () => {
  //TODO 表单校验
  const formData = staffForm.value
  console.log(originalFormData.value)
  console.log(formData)
  try {
    const i = getChangedFields(originalFormData.value, formData)
    let res;
    if (formId) {
      const upWrap = updateWrapperBuilder(formData, i); // 传递 formData 作为参数
      res = await _modifyStaffInfo(upWrap); // 使用 upWrap 作为参数
    } else {
      res = await _saveStaffInfo(formData);
      if (res.code === 200 && res.data) {
        formId = res.data[0];
        staffForm.value.id = formId;
      }
    }
    if (res && res.code === 200) {
      resetForm();
      //刷新操作记录
      const rres = await _getRecordInfos({ id: formId.toString() });
      if (rres.code === 200 && rres.data) {
        recordInfos.value = rres.data;
      }
    }
  } catch (error) {
    console.error('保存失败:', error);
  }
};
const resetForm = () => {
  originalFormData.value = JSON.parse(JSON.stringify(staffForm.value));
  detailsTitle.value = staffForm.value.staffName || '新建';
  isFormChanged.value = false;
}
// 撤销修改，还原表单
const handleRevert = () => {
  staffForm.value = JSON.parse(JSON.stringify(originalFormData.value));
};
//初始化加载数据
onMounted(async () => {
  detailsTitle.value = '新建'
  console.error(showDialog.value)
  //获取用户数据
  if (formId) {
    //编辑
    const res = await _getStaffInfo({ id: formId.toString() });
    if (res.code === 200 && res.data) {
      staffForm.value = res.data;
      originalFormData.value = JSON.parse(JSON.stringify(res.data));
      detailsTitle.value = staffForm.value.staffName || '';
    }
    const rres = await _getRecordInfos({ id: formId.toString() });
    console.log(rres.code);
    if (rres.code === 200 && rres.data) {
      recordInfos.value = rres.data;
    }
  }
  console.log("onMounted", staffForm.value)
});

const getDateRange = (val: string) => {
  console.log(val);
  if (!val) {
    staffForm.value.staffAssensmentDate = ''
  }
}

//发送备注消息
const sendRecordRemark = async () => {
  if (formId && recordRemark.value) {
    await _saveRecordRemarkInfos({
      bizId: formId.toString(),
      remark: recordRemarkInfo.value.toString(),
    })
    //刷新操作记录
    const rres = await _getRecordInfos({ id: formId.toString() });
    if (rres.code === 200 && rres.data) {
      recordInfos.value = rres.data;
    }
    recordRemarkInfo.value = '';
  }
}
//搜索备注内容
const recordSearching = async () => {
  if (formId && recordSearch.value) {
    const ress = await _searchRecordRemarkInfos({
      _search_bizid: formId.toString(),
      _search_content: recordSearchInfo.value
    })
    if (ress.code === 200 && ress.data) {
      recordInfos.value = ress.data;
    }
  }
}
const recordRemarkChoose = () => {
  recordRemark.value = !recordRemark.value;
  if (recordRemark.value) {
    nextTick(() => {
      const textarea = document.querySelector('.el-textarea__inner') as HTMLTextAreaElement;
      textarea.focus();
    });
  }
}

const recordSearchChoose = () => {
  recordSearch.value = !recordSearch.value;
  if (recordSearch.value) {
    nextTick(() => {
      if (searchRef.value) {
        const a = searchRef.value as HTMLTextAreaElement;
        a.focus();
      }
    });
  }
}
const tabHandleClick = (tab: TabsPaneContext, event: Event) => {
  if (tab && tab.props && typeof tab.props.name === 'string') {
    console.log(tab, event);
    console.log(tab.props.name);
    tabHandleClickName.value = tab.props.name;
    console.log(activeName.value);
  } else {
    console.error('无效的标签或标签名称');
  }
}

//是否打开业务选择器
const showDialog = ref(false);
const showDialogManager = ref(false);
//choose 组件配置
const {
  _dept_config_columns,
  _dept_query_wrapper_config
} = departmentConfig(staffForm.value.deptId?.toString() || '')
//choose 组件配置
const {
  _staff_config_columns,
  _staff_query_wrapper_config
} = staffManagerConfig(staffForm.value.manager?.toString() || '')

const handleSelectedDept = (val: DepartmentForm) => {
  console.log(val);
  //上级部门id
  staffForm.value.deptId = val.id ?? ''
  voForm.value.deptName = val.deptName ?? '未知名称'
}
const handleSelectedStaff = (val: StaffForm) => {
  console.log(val);
  //上级部门id
  staffForm.value.manager = val.id ?? ''
  voForm.value.managerName = val.staffName ?? '未知名称'
}
const changePIdClick = (val: string) => {
  if (val == 'dept') {
    showDialog.value = true;
  }
  if (val == 'staff') {
    showDialogManager.value = true;
  }
}
</script>
<style scoped>
:deep(.el-input__inner) {
  --el-input-inner-height: none;
}

:deep(.el-card__body) {
  padding: 1% !important;
  justify-content: unset !important;
}

.hover-icon {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.hover-icon:hover {
  transform: translateY(-2px);
}

.sub-title {
  font-size: 14px;
  color: #666;
}

.divider {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  margin-top: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.content-section {
  flex: 1;
  width: 100%;
  padding: 15px;
  background-color: #f5f5f5;
  box-sizing: border-box;
}
.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.demo-tabs {
  position: relative;
  width: 100%;
  overflow-y: auto;
}

:deep(.el-tabs__nav-wrap::after) {
  position: absolute;
  content: '';
  width: 100%;
  height: 2px;
  background-color: var(--el-border-color-light);
  bottom: 0;
  left: 0;
  z-index: 1;
}

:deep(.el-tabs__nav.is-top) {
  margin-left: 10px
}

:deep(.el-tabs__header) {
  width: 100%;
  margin-bottom: 0;
}

:deep(.el-tabs__nav-wrap) {
  width: 100%;
}

.avatar-uploader .avatar {
  width: 90px;
  height: 90px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 90px;
  height: 90px;
  text-align: center;
}

.el-form-item__label {
  color: black !important;
}

.el-tabs--border-card>.el-tabs__header {
  background-color: white !important
}

.el-tabs--border-card {
  border: 0px;
}

.el-tabs--border-card>.el-tabs__header .el-tabs__item {
  margin-top: 0px;
}

.el-tabs--border-card>.el-tabs__header .el-tabs__item.is-active {
  border-top-color: #922575;
}
</style>
